package com.example.wangzh.developkit.widget;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.wangzh.developkit.R;
import com.example.wangzh.developkit.constant.MathConstant;
import com.example.wangzh.developkit.utils.TransformUtils;
import com.example.wangzh.developkit.utils.input_filter.DecimalFilter;


import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by USER on 2017/1/17.
 */

public class AmountSelector extends LinearLayout implements View.OnClickListener {
    protected long downMilliSeconds, upMilliSeconds;
    TextView txt_stock_amount;
    ImageView img_minus, img_plus;
    EditText edt_require_amount;
    @BindView(R.id.img_clear)
    ImageView img_clear;
    @BindView(R.id.txt_title)
    TextView txt_title;
    OnAmountChangeListener onAmountChangeListener;
    double stockAmount = 500;
    double requireAmount = 0;

    public interface OnAmountChangeListener {
        void OnAmountChange(double amount);
    }

    public void setOnAmountChangeListener(OnAmountChangeListener onAmountChangeListener) {
        this.onAmountChangeListener = onAmountChangeListener;
    }

    public void setStockAmount(double stockAmount) {
        this.stockAmount = stockAmount;
        txt_stock_amount.setText("(库存" + TransformUtils.transformDouble(stockAmount) + "吨)");
    }

    public void setRequireAmount(double requireAmount) {
        this.requireAmount = requireAmount;
        edt_require_amount.setText(TransformUtils.transformDouble(requireAmount));
        edt_require_amount.setSelection(edt_require_amount.length());
    }

    public double getRequireAmount() {
        return requireAmount;
    }

    public AmountSelector(Context context) {
        super(context);
        initView(context);
    }


    public AmountSelector(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    protected void initView(Context context) {
        View view = LayoutInflater.from(context).inflate(R.layout.custom_amount_selector, this);
        ButterKnife.bind(this);
        txt_stock_amount = (TextView) view.findViewById(R.id.txt_stock_amount);
        img_minus = (ImageView) view.findViewById(R.id.img_minus);
        img_plus = (ImageView) view.findViewById(R.id.img_plus);
        edt_require_amount = (EditText) view.findViewById(R.id.edt_require_amount);
        if (isInEditMode()) {
            return;
        }
        new TouchDealer(img_minus, new TouchPerform() {
            @Override
            public void perform() {
                performMinus();
            }
        });
        new TouchDealer(img_plus, new TouchPerform() {
            @Override
            public void perform() {
                performPlus();
            }
        });
        img_minus.setOnClickListener(this);
        img_plus.setOnClickListener(this);
        edt_require_amount.setSelection(edt_require_amount.getEditableText().length());
        try {
            requireAmount = Double.parseDouble(edt_require_amount.getEditableText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        img_clear.setOnClickListener(this);
        edt_require_amount.setFilters(new InputFilter[]{new DecimalFilter(2), new InputFilter.LengthFilter(7)});
        edt_require_amount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    img_clear.setVisibility(INVISIBLE);
                    img_clear.setClickable(false);
                } else {
                    img_clear.setVisibility(VISIBLE);
                    img_clear.setClickable(true);
                    try {
                        requireAmount = Double.parseDouble(s.toString());
                        if (onAmountChangeListener != null) {
                            onAmountChangeListener.OnAmountChange(requireAmount);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_minus:
                performMinus();
                break;
            case R.id.img_plus:
                performPlus();
                break;
            case R.id.img_clear:
                setRequireAmount(0);
                edt_require_amount.setText("");
                break;
            default:
                break;
        }
    }


    protected void performPlus() {
        if (Math.abs(requireAmount - stockAmount) < MathConstant.SMALL) {
            return;
        }
        requireAmount += 1;
        if (requireAmount > stockAmount) {
            requireAmount = stockAmount;
        } else if (requireAmount < 0) {
            requireAmount = 0;
        }
        setRequireAmount(requireAmount);
        if (onAmountChangeListener != null) {
            onAmountChangeListener.OnAmountChange(requireAmount);
        }
    }

    protected void performMinus() {
        if (Math.abs(requireAmount) < MathConstant.SMALL) {
            return;
        }
        requireAmount -= 1;
        if (requireAmount < 0) {
            requireAmount = 0;
        } else if (requireAmount > stockAmount) {
            requireAmount = stockAmount;
        }
        setRequireAmount(requireAmount);
        if (onAmountChangeListener != null) {
            onAmountChangeListener.OnAmountChange(requireAmount);
        }
    }

    public interface TouchPerform {
        public void perform();
    }

    private class TouchDealer {
        View view;
        TouchPerform touchPerform;
        TouchHandler touchHandler;

        TouchDealer(View view, TouchPerform touchPerform) {
            this.view = view;
            this.touchPerform = touchPerform;
            touchHandler = new TouchHandler(touchPerform);
            view.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            downMilliSeconds = System.currentTimeMillis();
                            touchHandler.sendEmptyMessage(0);
                            break;
                        case MotionEvent.ACTION_UP:
                            upMilliSeconds = System.currentTimeMillis();
                            touchHandler.sendEmptyMessage(1);
                            //如果按下松开间隔小于500毫秒，则判定不是长按连续事件，直接执行onClick
                            //由于这是自定义控件的内部类所以可以直接调用onClick，否则可以将其并入TouchPerform中
                            if (upMilliSeconds - downMilliSeconds < 500) {
                                onClick(v);
                            }
                    }
                    return true;
                }
            });
        }
    }

    private static class TouchHandler extends Handler {
        TouchPerform touchPerform;
        boolean cancled = false;

        TouchHandler(TouchPerform touchPerform) {
            this.touchPerform = touchPerform;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0://接收到消息为0，设为未取消，并且准备500毫秒之后激发长按连续事件
                    cancled = false;
                    sendEmptyMessageDelayed(2, 500);
                    break;
                case 1://接受到消息为1，设为已取消
                    cancled = true;
                    break;
                case 2://接收到消息为2，如果是未取消状态，则激发长按连续事件并且100毫秒之后再次激发
                    if (!cancled) {
                        if (touchPerform != null) {
                            touchPerform.perform();
                        }
                        sendEmptyMessageDelayed(2, 100);
                    }
            }
        }
    }
}
